package com.central.apps.handler;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.apps.common.util.DateUtiles;
import com.central.common.util.ToolUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 处理资产台账业务逻辑
 *
 * @author lidachao
 * @date 2022/8/1
 */
@Component
public class AssetheadHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        String assetnum = MapUtils.getString(data,"assetnum");
        List<Map<String, Object>> bySql = handlerService.findBySql("select useryear,productiontime,assetnum,description,location,locationdesc,nickname from gq_assethead gq left join sys_user sys on gq.assetuser =sys.username  where gq.assetnum ='" + assetnum + "';");
        String infos ="资产编码:"+MapUtils.getString(bySql.get(0),"assetnum")+"\r\n"
                    + "资产描述:"+MapUtils.getString(bySql.get(0),"description")+"\r\n"
                    + "位置编码:"+MapUtils.getString(bySql.get(0),"location")+"\r\n"
                    + "位置描述:"+MapUtils.getString(bySql.get(0),"locationdesc")+"\r\n"
                    + "负责人:"+MapUtils.getString(bySql.get(0),"nickname");
        //更新二维码信息
        String updInfosSql = "update gq_assethead set infos ='" + infos+"' where assetnum ='" + assetnum + "';";
        handlerService.updateBySql(updInfosSql);
        // 1.获取参数数据
        Map map = bySql.get(0);
        int useryear = (int) map.get("useryear");
        java.sql.Timestamp productiontime = (java.sql.Timestamp) map.get("productiontime");

        // 2.计算资产剩余寿命(月)：使用寿命-（当前时间-投产时间）
        Date currentDate = new Date();
        if(ToolUtil.isNotEmpty(productiontime)){
            int intervalMonth = DateUtiles.calIntervalMonth(productiontime, currentDate);

            if (intervalMonth > useryear) {
                intervalMonth = 0;
            } else {
                intervalMonth = useryear - intervalMonth;
            }

            // 3.更新资产台账资产剩余寿命(月)&sql信息
            String updSql = "update gq_assethead set surpluslife ='" + intervalMonth + "', infos ='" + infos+"'"
                    + " where assetnum ='" + assetnum + "';";
            handlerService.updateBySql(updSql);
        }
    }
}
